package br.ufal.tci.nexos.arcolive.service.broker.command;

import br.ufal.tci.nexos.arcolive.command.ArCoLIVEClientCommand;
import br.ufal.tci.nexos.arcolive.command.ArCoLIVECommandResult;
import br.ufal.tci.nexos.arcolive.exception.ArCoLIVEException;
import br.ufal.tci.nexos.arcolive.exception.ArCoLIVEPersistenceException;
import br.ufal.tci.nexos.arcolive.participant.ArCoLIVEParticipant;
import br.ufal.tci.nexos.arcolive.persistence.ArCoLIVEPersistence;
import br.ufal.tci.nexos.arcolive.persistence.ArCoLIVEPersistenceConnectionPoll;
import br.ufal.tci.nexos.arcolive.service.connection.ConnectionRequest;

public class SetParticipantProfileCommand extends ArCoLIVEClientCommand {
	
	public SetParticipantProfileCommand(ConnectionRequest request) {
		super(request);
	}
	
	public ArCoLIVECommandResult executeImpl() {
		ArCoLIVEParticipant participant = (ArCoLIVEParticipant)this.request.getOwner();
		int participantId = this.request.getIntegerParameter("participantId").intValue();
		String response = "";
		
		if (participantId == participant.getParticipantDescriptor().getParticipantId()) {
			
			String fullname = this.request.getStringParameter("fullname");
			String email = this.request.getStringParameter("email");
			String username = this.request.getStringParameter("username");
			String password = this.request.getStringParameter("password");
			String location = this.request.getStringParameter("location");
			String city = this.request.getStringParameter("city");
			String state = this.request.getStringParameter("state");
			String msnId = this.request.getStringParameter("msnId");
			String yahooId = this.request.getStringParameter("yahooId");
			String aolId = this.request.getStringParameter("aolId");
			
			int countryId = 0;
			try {
				countryId = this.request.getSafelyIntegerParameter("countryId").intValue();
			} catch (ArCoLIVEException e) {	}
			
			try {
				ArCoLIVEPersistenceConnectionPoll pcp = ArCoLIVEPersistenceConnectionPoll.getInstance();
				ArCoLIVEPersistence persistence = pcp.getDatabaseConnection();
				boolean updateResult = persistence.updateParticipant(participantId, fullname, email, username, password, null,
											  location, city, state, countryId, msnId, yahooId, aolId);
				pcp.addDatabaseConnection(persistence);
				response = (updateResult) ? "1" : "0";
	
			} catch (ArCoLIVEPersistenceException alpe) {
				response = "0";
				return new ArCoLIVECommandResult(this, response, alpe);
			}
			
		} else {
			response = "0";
			return new ArCoLIVECommandResult(this, response, new ArCoLIVEException("Participant doesn't have permission"));
		}
		
		return new ArCoLIVECommandResult(this, response);
	}

}